package com.hx.vending.util;

import com.alibaba.fastjson.JSONObject;
import com.hx.vending.bean.Equipment;
import com.hx.vending.bean.Field;
import com.hx.vending.bean.User;
import com.hx.vending.dao.EquipmentMapper;
import com.hx.vending.dao.FieldMapper;
import com.hx.vending.dao.UserMapper;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/3/27.
 */
public class flowcardMonitor {

    private Logger logger = Logger.getLogger(payOverTime.class); // 获取logger实例

    @Resource
    private EquipmentMapper equipmentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private FieldMapper fieldMapper;

    public void flowcardMonitor(){

        logger.error("//////////////////////////////////物联卡监测开始///////////////////////////////");

        //Authorization所需用户密码
        String authorization = Base64Util.baseEncode(Constant.IOTCARD_APPKEY+":"+Constant.IOTCARD_APPSECRET);//base64一行不能超过76字符，超过则添加回车换行符
        authorization = authorization.replaceAll("[\\s*\\t\\n\\r]", "");

        //////////////查询单张物联卡的信息///////////////

        //查询数据库拥有物联卡的设备
        List<Equipment> equipmentList = this.equipmentMapper.selectFlowcardNotNull();

        if (ToolUtil.isNotEmpty(equipmentList)) {

            for (Equipment equipment:equipmentList) {

                if (ToolUtil.isNotEmpty(equipment.getEquipmentFlowcard())) {
                    //查询物联卡信息
                    Map<String, Object> cardMap = new HashMap<>();
                    cardMap.put("imsi", equipment.getEquipmentFlowcard());
                    Map<String, Object> cardResultMap = SendRequest.SendFlowRequest(Constant.IOTCARD_CARD, cardMap, "POST", authorization);
                    if (ToolUtil.isNotEmpty(cardResultMap)) {
                        if (cardResultMap.get("code").toString().equals("0")) {
                            String cardJsonStr = cardResultMap.get("data").toString();
                            cardJsonStr = cardJsonStr.replace("[", "");
                            cardJsonStr = cardJsonStr.replace("]", "");
                            Map<String, Object> cardResultDataMap = (Map<String, Object>) JSONObject.parse(cardJsonStr);

                            //超过套餐的80%推送提醒
                            if (BigDecimalUtils.mul(Double.parseDouble(cardResultDataMap.get("data_plan").toString()), 0.2) >= Double.parseDouble(cardResultDataMap.get("data_balance").toString())) {

                                //用户
                                User user = new User();
                                user.setUserId(equipment.getEquipmentUserId());
                                User selectUser = this.userMapper.selectByPrimaryKey(user);

                                //场地
                                Field field = new Field();
                                field.setFieldId(equipment.getEquipmentFieldId());
                                Field selectField = fieldMapper.selectByPrimary(field);

                                if(ToolUtil.isNotEmpty(selectUser) && ToolUtil.isNotEmpty(selectField)){
                                    String pushMessage = "物联卡监测:\n设备ID:%s\n场地名称:%s\n编号:%s\n地区:%s\n详细地址:%s\n物联卡套餐:%s\n剩余流量:%s\n物联卡套餐余量低于80%%，请尽快充值！！";
                                    try {
                                        PushUtils.getInstance().pushMessage(selectUser.getUserAccount(), String.format(pushMessage, equipment.getEquipmentId(),
                                                selectField.getFieldName(),equipment.getEquipmentNumber() + "-号机", selectField.getFieldRegion(), selectField.getFieldAddress(),
                                                cardResultDataMap.get("data_plan").toString()+"M", cardResultDataMap.get("data_balance").toString()+"M"));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }


        //////////////查询流量池总量的信息//////////////


        //查询计费组列表
        Map<String, Object> resultMap = SendRequest.SendFlowRequest(Constant.IOTCARD_BILLING_GROUP, new HashMap(), "POST", authorization);

        //获取计费组信息
        List<Map<String, Object>> billingGroupList = null;
        if (ToolUtil.isNotEmpty(resultMap)) {
            if (resultMap.get("code").toString().equals("0")) {
                billingGroupList = (List<Map<String, Object>>) JSONObject.parse(resultMap.get("data").toString());
            }
        }

        if (ToolUtil.isNotEmpty(billingGroupList)) {

            Double totalFlowPool = 0.00;//总流量池
            Double flowConsume = 0.00;//流量消耗
            Double surplusFlow = 0.00;//剩余流量

            //根据计费组的bg_code查询流量
            for (Map group: billingGroupList) {

                //查询该计费组下的物联卡信息(需要判断页码)
                A:for (int i = 1; i > 0; i++) {
                    Map<String, Object> paramsMap = new HashMap<>();
                    paramsMap.put("bg_code", group.get("bg_code"));//流量组编号
                    paramsMap.put("page", i);//页码
                    paramsMap.put("psize", 100);//数量
                    Map<String, Object> cardListMap = SendRequest.SendFlowRequest(Constant.IOTCARD_CARDLIST, paramsMap, "POST", authorization);
                    if (ToolUtil.isNotEmpty(cardListMap)) {
                        if (cardListMap.get("code").toString().equals("0")) {
                            //获得所有卡的集合
                            List<Map<String, Object>> allCardMsg = (List<Map<String, Object>>) JSONObject.parse(cardListMap.get("data").toString());

                            totalFlowPool += BigDecimalUtils.mul(allCardMsg.size(), Double.parseDouble(allCardMsg.get(0).get("data_plan").toString()));

                            //循环所有卡
                            for (Map card: allCardMsg) {
                                surplusFlow += Double.parseDouble(card.get("data_balance").toString());
                            }

                            //判断页码(当前页大于等于总页数跳出循环)
                            if (Integer.parseInt(cardListMap.get("page").toString())>=Integer.parseInt(cardListMap.get("num_pages").toString())) {
                                break A;
                            }
                        }
                    }
                }
            }

            //消耗超过80%推送提醒
            if (surplusFlow <= BigDecimalUtils.mul(totalFlowPool, 0.2)) {
                String pushMessage = "物联卡监测:\n物联卡流量池:%s\n剩余流量:%s\n物联卡流量池余量低于80%%,请尽快充值！！";
                String[] userAccount = new String[]{"18654568090", "15562649697", "15288932468", "13589090932"};
                for (String account:userAccount) {
                    try {
                        PushUtils.getInstance().pushMessage(account, String.format(pushMessage, BigDecimalUtils.round(totalFlowPool,1,2)+"M", BigDecimalUtils.round(surplusFlow,1,2)+"M"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        logger.error("//////////////////////////////////物联卡监测结束///////////////////////////////");


    }
}
